import 'package:json_annotation/json_annotation.dart';

part 'order_item.g.dart';

@JsonSerializable()
class OrderItem {
  @JsonKey(fromJson: _toInt, defaultValue: 0)
  final int goodsId;

  @JsonKey(fromJson: _toInt, defaultValue: 0)
  final int skuId;

  @JsonKey(defaultValue: '')
  final String name;

  @JsonKey(name: 'img', defaultValue: '')
  final String imageUrl;

  /// 后端返回可能是 null/int/double/string，这里兼容并重命名
  @JsonKey(name: 'unitPrice', fromJson: _toDouble, defaultValue: 0.0)
  final double price;

  @JsonKey(fromJson: _toInt, defaultValue: 0)
  final int quantity;

  @JsonKey(fromJson: _toInt, defaultValue: 0)
  final int merchantId;

  const OrderItem({
    required this.skuId,
    required this.goodsId,
    required this.name,
    required this.imageUrl,
    required this.price,
    required this.quantity,
    required this.merchantId,
  });

  factory OrderItem.fromJson(Map<String, dynamic> json) =>
      _$OrderItemFromJson(json);

  Map<String, dynamic> toJson() => _$OrderItemToJson(this);

  // ---------- 辅助函数，保证健壮 ----------
  static int _toInt(Object? v) {
    if (v == null) return 0;
    if (v is int) return v;
    if (v is double) return v.toInt();
    if (v is String && v.trim().isNotEmpty) {
      return int.tryParse(v) ?? double.tryParse(v)?.toInt() ?? 0;
    }
    return 0;
  }

  static double _toDouble(Object? v) {
    if (v == null) return 0.0;
    if (v is double) return v;
    if (v is int) return v.toDouble();
    if (v is String && v.trim().isNotEmpty) {
      return double.tryParse(v) ?? 0.0;
    }
    return 0.0;
  }
}
